package org.china.lanzhou.structure.convey;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 原始表述,交互层构建意图
 * -----------------------
 * 双点表示法：目标  结果
 * 三点表示法：目标  过程  结果
 *
 * 词组成
 *  句{
 *     词组{ 词1  >  词2,
 *      词组{ 词3  >  词4,
 *       词组{ 词5  >  词4,
 *        词组{ 词4  <  词6,
 *
 */
public class OriginalConvey {


    private List<Phrase> phraseList = new LinkedList<>();

    private Phrase addPhrase(Phrase phrase){
        if(phraseList.indexOf(phrase)<0){
            phraseList.add(phrase);
        }
        return phraseList.get(phraseList.indexOf(phrase));
    }

    public Phrase addPhrase(String word){
        if(StringUtils.isNotEmpty(word))
        return addPhrase(new Phrase(word));
        return null;
    }

    public void addPhrase(String word,String guide){
        Phrase g = addPhrase(guide);
        Phrase w = addPhrase(word);
        guidePhrase(w,g);
    }

    public void guidePhrase(Phrase phrase,Phrase guide){
        if(phrase.getGuide()==null)
        phrase.setGuide(guide);
    }


    public void parse(String str){
        str = StringUtils.upperCase(str);
        Map<String,String> wordMap ;
        for (String s : str.split(" ")) {
            wordMap = new LinkedHashMap<>();
            String[] sps= s.split("->");
            String afters = null;

            for (String sp : sps) {
                if(sp.indexOf(',')>=0){
                    for (String s1 : sp.split(",")) {
                        wordMap.put(s1,null);
                    }
                }else{
                    wordMap.put(sp,null);
                }
                if(afters!=null){
                    if(afters.indexOf(",")>=0){
                        for (String s1 : afters.split(",")) {
                            wordMap.put(s1,sp);
                        }
                    }else{
                        wordMap.put(afters,sp);
                    }
                }
                afters = sp;
            }
            ListIterator<Map.Entry<String,String>> i = new ArrayList<Map.Entry<String,String>>(wordMap.entrySet()).listIterator(wordMap.size());
            while(i.hasPrevious()) {
                Map.Entry<String, String> entry=i.previous();
                addPhrase(entry.getKey(),entry.getValue());
            }
        }

    }

    public Phrase[] getPhraseArr() {
        return phraseList.toArray(new Phrase[phraseList.size()]);
    }

    public static void main(String[] args) {
        OriginalConvey originalConvey = new OriginalConvey();
        originalConvey.parse(
                ":c1:abc->:c2:iio c3->c4 c5,c8->c6->c7"
        );
        for (Phrase phrase : originalConvey.getPhraseArr()) {
            System.out.println(phrase);
        }
    }

}
